package org.edu.bean;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.edu.model.Student;
import org.edu.model.StudentLesson;
import org.edu.model.User;
import org.edu.service.StudentLessonService;
import org.edu.service.UserService;
import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
@SessionScoped
public class UserLoginBean implements Serializable {

	private static final long serialVersionUID = 1L;
	@Autowired
	private transient UserService userService;
	@Autowired
	private transient StudentLessonService studentLessonService;
	private User user;
	private StudentLesson studentLesson;
	private Boolean remember;
	private List<User> users;
	private List<Student> students;
	private List<StudentLesson> listMyLesson;

	public UserLoginBean() {
		user = new User();
	}
	
	@PostConstruct
	public void init(){
		users = userService.users();
		listMyLesson = studentLessonService.studentLessons();
	}
	public void preparedAddingUser(){
		user = new User();
	}

	public String Login() throws Exception {
		RequestContext context = RequestContext.getCurrentInstance();
		FacesMessage msg = null;
		boolean loggedIn = false;

		user = userService.getUser(user);
		if (user != null) {
			if(user.getStatus() == true){
				loggedIn = true;
				msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome",	user.getUser_number());
				return "home";
			}else{
				loggedIn = false;
				msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Your account is passive!",	"Login Error");
			}
		} else{
			loggedIn = false;
			msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Invalid Username or Password!",	"Login Error");
		}

		FacesContext.getCurrentInstance().addMessage(null, msg);
		context.addCallbackParam("loggedIn", loggedIn);
		return "login";
	}

	public User getUser() {
		if (user == null) {
			user = new User();
		}
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	public List<User> getUsers() {
		return users;
	}
	
	public StudentLesson getStudentLesson() {
		if(studentLesson == null){
			studentLesson = new StudentLesson();
		}
		return studentLesson;
	}

	public void setStudentLesson(StudentLesson studentLesson) {
		this.studentLesson = studentLesson;
	}

	public Boolean isRemember() {
		return remember;
	}

	public void setRemember(Boolean remember) {
		this.remember = remember;
	}

	public List<Student> getStudents() {
		return students;
	}

	public List<StudentLesson> getListMyLesson() {
		return listMyLesson;
	}

}
